package com.superMall.service;

import com.google.common.collect.Lists;
import com.superMall.util.FTPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


/**
 * Created by guanwei on 2017/11/20.
 */

@Service("iFileService")
public class FileServiceImpl implements IFileService {

    public static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    public String upload(MultipartFile file,String path){

        String fileName = file.getOriginalFilename();
        //扩展名
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);
        //重新对上传的文件命名，避免名字重复
        String upLoadFileName = UUID.randomUUID().toString() + "." + fileExtensionName;
        logger.info("开始上传文件，文件名：{},上传路径{}，重新命名后的文件名：{}",fileName,path,upLoadFileName);

        File fileDir = new File(path);
        if(!fileDir.exists()){
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File targetFile = new File(path,upLoadFileName);

        try {
            file.transferTo(targetFile);
            //文件上传成功
            FTPUtil.upLoadFile(Lists.newArrayList(targetFile));
            //已经上传到FTP服务器中
            //删除服务器里的文件
            targetFile.delete();
        } catch (IOException e) {
            logger.error("文件上传出现异常",e);
            return null;
        }
        return targetFile.getName();
    }
}
